package com.licq.ldoc.writer.visitor.example.exampler;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.licq.ldoc.domain.Element;
import com.licq.ldoc.domain.ElementType;
import com.licq.ldoc.domain.ElementType.MapElementType;
import com.licq.ldoc.utils.ClassUtils;
import com.licq.ldoc.writer.visitor.example.Exampler;

/**
 * 
 * @author liujian
 *
 */
public class MapperAttributeElementExampler extends Exampler {
	
	private org.dom4j.Element domElement;

	private Object object;

	private Element element;

	public MapperAttributeElementExampler(org.dom4j.Element domElement,
			Object object, Element element) {
		this.domElement = domElement;
		this.object = object;
		this.element = element;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void create() {
		String property = element.getName();
		Map propertyValue = (Map) getPropertyValue(object, property);
		if (propertyValue == null && element.isRequired()) {
			propertyValue = mockPropertyValue();
		}
		if (propertyValue != null) {
			org.dom4j.Element ele = domElement.addElement(property);
			for (Object entryObj : propertyValue.entrySet()) {
				@SuppressWarnings("unused")
				Entry entry = (Entry) entryObj;
				org.dom4j.Element entryEle = ele.addElement("entry");
				org.dom4j.Element keyEle = entryEle.addElement("key");
				keyEle.addElement(getKeyType().getClazz().getSimpleName());
				org.dom4j.Element valueEle = entryEle.addElement("value");
				valueEle.addElement(getValueType().getClazz().getSimpleName());
				//尚无法往下举例,结构不支持，没有nest element信息
			}
		}
	}

	@SuppressWarnings("unchecked")
	private Map mockPropertyValue() {
		Map map = new HashMap();
		ElementType keyType = getKeyType();
		ElementType valueType = getValueType();
		map.put(ClassUtils.newInstance(keyType.getClazz()), 
				ClassUtils.newInstance(valueType.getClazz()));
		return map;
	}

	private ElementType getKeyType() {
		return ((MapElementType) element.getType()).getKeyElementType();
	}
	
	private ElementType getValueType() {
		return ((MapElementType) element.getType()).getValueElementType();
	}

}
